#include "main_window.h"
#include "ui_main_window.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->dialogCreate = new DialogCreate(this);
    addConnection();
}

MainWindow::~MainWindow()
{
    QSerialPort* port;
    for (int i=0; i< ui->tabWidget->count(); i++){
        port = ((SerialWidget*)ui->tabWidget->widget(i))->serialPort();
        port->close();
        delete port;
    }
    ui->tabWidget->clear();
    delete ui;
}

void MainWindow::addConnection()
{
    if (this->dialogCreate->exec() == QDialog::Accepted) {
        QSerialPort* port = new QSerialPort(this);
        port->setPortName(this->dialogCreate->portName());
        port->setBaudRate(this->dialogCreate->baudRate());
        port->setParity(this->dialogCreate->parity());
        port->setDataBits(this->dialogCreate->dataBits());
        port->setStopBits(this->dialogCreate->stopBits());
        if (port->open(QSerialPort::ReadWrite)) {
            SerialWidget* widget = new SerialWidget();
            widget->setSerialPort(port);

            ui->tabWidget->setCurrentIndex(ui->tabWidget->addTab(widget, port->portName()));
        }
        else {
            QMessageBox::critical(this, tr("open serial port faild"), port->errorString(), QMessageBox::Ok);
            delete port;
        }
    }
}
void MainWindow::on_actionAdd_triggered()
{
    addConnection();
}

void MainWindow::on_actionClose_triggered()
{
    QSerialPort* port;
    port = ((SerialWidget*)ui->tabWidget->currentWidget())->serialPort();
    port->close();
    delete port;
    ui->tabWidget->removeTab(ui->tabWidget->currentIndex());
}

void MainWindow::on_actionCloseAll_triggered()
{
    QSerialPort* port;
    for (int i=0; i< ui->tabWidget->count(); i++){
        port = ((SerialWidget*)ui->tabWidget->widget(i))->serialPort();
        port->close();
        delete port;
    }
    ui->tabWidget->clear();
}

void MainWindow::on_tabWidget_tabCloseRequested(int index)
{
    QSerialPort* currentPort = ((SerialWidget*)ui->tabWidget->widget(index))->serialPort();
    currentPort->close();
    delete currentPort;
    ui->tabWidget->removeTab(index);
}

